package com.yearno.common.utils

import android.text.Editable
import android.text.InputFilter
import android.text.Selection
import android.text.TextWatcher
import android.widget.EditText
import java.text.DecimalFormat

enum class FormatUtil {
    INSTANCE;

    fun getFormatFloat(float: Float?): String {
//val df = DecimalFormat("###,##0.00")
//val df = DecimalFormat("0.00") //格式化小数
//val df = DecimalFormat("#0.00")//与上一行代码的区别是：#表示如果不存在则显示为空，0表示如果没有则该位补0.
//val df = DecimalFormat("#0.00")//与上一行代码的区别是：#表示如果不存在则显示为空，0表示如果没有则该位补0.
        val df = DecimalFormat("#,##0.00") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        return df.format(float)
    }

    fun getFormatDouble(double: Double?): String {
        val df = DecimalFormat("#,##0.00") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        return df.format(double)
    }

    fun getFormatMoney(int: Int?): String {
        val df = DecimalFormat("#,##0") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        return df.format(int)
    }

    fun getFormatLong(long: Long?): String {
        val df = DecimalFormat("#,##0") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        return df.format(long)
    }

    fun getFormatDoubleStr(doubleStr: String?): String {
        val df = DecimalFormat("#,##0.00") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        return df.format(doubleStr?.toDouble())
    }

    fun formatListRate(floatStr: String?): String {
        val df = DecimalFormat("0.00") //将数据转换成以3位逗号隔开的字符串，并保留两位小数
//        df.roundingMode = RoundingMode.FLOOR //不四舍五入
        val percent = floatStr?.toFloat()?:0f
        return df.format(percent * 100)+"%"
    }

    fun getFormatDoubleWan(double: Double?): String? {
        var wanStr = "0"
        double?.let {
            wanStr = if (it < 10000) {
                getFormatDouble(it)
            } else {
                getFormatDouble(it / 10000.0) + "万"
            }
        }
        return wanStr
    }

    fun getFormatLongStrWan(longStr: String?): String? {
        var wanStr = "0"
        longStr?.let {
            val num = it.toLong()
            wanStr = if (num < 10000) {
                getFormatLong(num)
            } else {
                getFormatDouble(num / 10000.0) + "万"
            }
        }
        return wanStr
    }

    /**
     * 设置银行卡输入时每隔4位多一位空格
     * @param cardEt
     */
    fun formatBankCardInput(cardEt: EditText) {
        //设置输入长度不超过24位(包含空格)
        cardEt.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(24))
        cardEt.addTextChangedListener(object : TextWatcher {
            var kongge = ' '

            //改变之前text长度
            var beforeTextLength = 0

            //改变之前的文字
            private val beforeChar: CharSequence? = null

            //改变之后text长度
            var onTextLength = 0

            //是否改变空格或光标
            var isChanged = false

            // 记录光标的位置
            var location = 0
            var tempChar: CharArray? = null
            val buffer = StringBuffer()

            //已有空格数量
            var konggeNumberB = 0
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                beforeTextLength = s.length
                if (buffer.length > 0) {
                    buffer.delete(0, buffer.length)
                }
                konggeNumberB = 0
                for (i in 0 until s.length) {
                    if (s[i] == ' ') {
                        konggeNumberB++
                    }
                }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                onTextLength = s.length
                buffer.append(s.toString())
                if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                    isChanged = false
                    return
                }
                isChanged = true
            }

            override fun afterTextChanged(s: Editable) {
                if (isChanged) {
                    location = cardEt.selectionEnd
                    var index = 0
                    while (index < buffer.length) {
                        if (buffer[index] == kongge) {
                            buffer.deleteCharAt(index)
                        } else {
                            index++
                        }
                    }
                    index = 0
                    var konggeNumberC = 0
                    while (index < buffer.length) {
                        if (index == 4 || index == 9 || index == 14 || index == 19) {
                            buffer.insert(index, kongge)
                            konggeNumberC++
                        }
                        index++
                    }
                    if (konggeNumberC > konggeNumberB) {
                        location += konggeNumberC - konggeNumberB
                    }
                    tempChar = CharArray(buffer.length)
                    buffer.getChars(0, buffer.length, tempChar, 0)
                    val str = buffer.toString()
                    if (location > str.length) {
                        location = str.length
                    } else if (location < 0) {
                        location = 0
                    }
                    cardEt.setText(str)
                    val etable = cardEt.text
                    Selection.setSelection(etable, location)
                    isChanged = false
                }
            }
        })
    }


    fun maxIntInput(inputEt: EditText, min: Int, max: Int, maxLength: Int = 9) {
        //设置输入长度不超过9位(包含空格)
        inputEt.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(maxLength))
        inputEt.addTextChangedListener(object : TextWatcher {

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!s.isNullOrBlank()) {
                    val score = s.toString().toInt()
                    if (score > max) {
                        inputEt.setText(max.toString())
                    } else if (score < min) {
                        inputEt.setText(min.toString())
                    }
                }
            }

            override fun afterTextChanged(s: Editable) {
            }
        })
    }

    fun maxDoubleInput(inputEt: EditText, minStr: String, maxStr: String, maxLength: Int = 13) {
        //设置输入长度不超过9位(包含空格),默认两位小数
        inputEt.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(maxLength), MoneyValueFilter())
        inputEt.addTextChangedListener(object : TextWatcher {

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    if (!s.isNullOrBlank()) {
                        val score = s.toString().toDouble()
                        if (score > maxStr.toDouble()) {
                            inputEt.removeTextChangedListener(this)
                            inputEt.setText(maxStr)
                            inputEt.addTextChangedListener(this)
                        } else if (score < minStr.toDouble()) {
                            inputEt.removeTextChangedListener(this)
                            inputEt.setText(minStr)
                            inputEt.addTextChangedListener(this)
                        }
                    }
                }catch (e: Exception){
                    e.printStackTrace()
                }
            }

            override fun afterTextChanged(s: Editable) {
            }
        })
    }
}